package com.itheima.service;

import com.itheima.common.Code;
import com.itheima.common.CustomException;
import com.itheima.common.JsonResult;
import com.itheima.common.SnowFlake;
import com.itheima.mapper.admin.CategoryMapper;
import com.itheima.mapper.admin.DishMapper;
import com.itheima.mapper.admin.SetmealMapper;
import com.itheima.pojo.admin.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.smartcardio.CardException;
import java.util.List;

/**
 * @author ChenJunJie
 * @date 2022/6/14 14:30
 * 菜品的service层
 */
@Service
@Slf4j
public class DishService {
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private SnowFlake snowFlake;
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private SetmealMapper setmealMapper;

    //新增菜品
    public JsonResult<String> dishAdd(Dish<Flavors> dish, HttpServletRequest request) {

        //创建人
        String token = request.getHeader("Authorization");
        String username = redisTemplate.opsForValue().get(token);


        //设置菜品创建人
        dish.setCreateUser(username);

        //设置当前彩屏绑定的分类的类型
        Category category = categoryMapper.categorySelectById(dish.getCategoryId());
        dish.setType(category.getType());

        //为菜品加上雪花id
        long dishId = snowFlake.nextId();
        dish.setId(dishId + "");

        int dishNum = dishMapper.dishAdd(dish);

        //将菜品类中的口味类抽离出来进行添加
        int flavorNum = 0;
        List<Flavors> flavor = dish.getFlavors();

        for (Flavors flavors : flavor) {

            //设置口味创建人
            flavors.setCreateUser(username);

            //为口味关联当前添加的菜品的id
            flavors.setDishId(dishId + "");

            //为口味加上雪花id
            long flavorId = snowFlake.nextId();
            flavors.setId(flavorId + "");

            flavorNum = dishMapper.flavorsAdd(flavors);
        }


        if (dishNum > 0) {
            return JsonResult.success("新增菜品成功");
        }else {
            return JsonResult.error("新增菜品失败");
        }
    }

    //菜品分页查询
    public JsonResult<Pagination<Dish<Flavors>>> dishPagination(String name, Integer page, Integer pageSize, String type) {

        Integer index = (page - 1) * pageSize;

        String newName = name;
        if (name != null) {
            newName = "%" + name + "%";
        }

        List<Dish<Flavors>> disheList = dishMapper.dishSelectByNameAndType(newName, type);

        List<Dish<Flavors>> dishes = dishMapper.dishPagination(newName, index, pageSize, type);

        //获取菜品分类名存入菜品类中
        for (Dish<Flavors> dish : dishes) {
            Category category = categoryMapper.categorySelectById(dish.getCategoryId());
            dish.setCategoryName(category.getName());
        }


        Pagination<Dish<Flavors>> eps = new Pagination<Dish<Flavors>>();
        eps.setRecords(dishes);
        eps.setTotal(disheList.size());
        eps.setSize(pageSize);
        eps.setCurrent(page);

        if (disheList.size() <= 0 || dishes.size() <= 0) {
            return JsonResult.employeePaginationSuccess(eps,"查询失败,暂无数据");
        }

        return JsonResult.employeePaginationSuccess(eps, "查询成功");
    }

    //通过id查询菜品
    public JsonResult<Dish<FlavorsById>> dishSelectById(String id) {

        Dish<FlavorsById> dishByIds = dishMapper.dishSelectById(id);


        //查询口味
        List<FlavorsById> flavorsByIds = null;
        if (dishByIds != null) {
            flavorsByIds = dishMapper.flavorsSelectById(dishByIds.getId());
            //将查到的口味放进dishByIds类中
            dishByIds.setFlavors(flavorsByIds);
        }


        if (dishByIds != null) {
            return JsonResult.select(dishByIds, "查询成功");
        } else {
            return JsonResult.error("查询菜品失败");
        }
    }

    //通过菜品id修改菜品
    public JsonResult<String> dishUpdateById(Dish<Flavors> dish, HttpServletRequest request) {

        String token = request.getHeader("Authorization");
        String username = redisTemplate.opsForValue().get(token);

        dish.setUpdateUser(username);

        int dishNum = dishMapper.dishUpdateById(dish);

        //删除当前菜单下的口味，再重新将集合中的口味新增
        dishMapper.flavorsDeleteById(dish.getId());

        List<Flavors> flavors = dish.getFlavors();


        int flavorNum = 0;
        for (Flavors flavor : flavors) {
            //如果有id，则直接进行新增操作
            if (flavor.getId() != null) {

                flavor.setUpdateUser(username);

                flavorNum = dishMapper.flavorsAdd(flavor);
            } else {
                //如果没有id，则添加数据后进行新增操作

                //设置口味创建人
                flavor.setCreateUser(username);

                //为口味关联当前添加的菜品的id
                flavor.setDishId(dish.getId() + "");

                //为口味加上雪花id
                long flavorId = snowFlake.nextId();
                flavor.setId(flavorId + "");

                flavorNum = dishMapper.flavorsAdd(flavor);
            }

        }

        if (dishNum > 0) {
            return JsonResult.success("修改菜品成功");

        } else {
            return JsonResult.error("修改菜品失败");
        }

    }

    //通过菜品id删除
    public JsonResult<String> dishDeleteById(String ids) {

        //如果有多条id，分割其逗号
        String[] split = ids.split(",");

        int count = 0;
        for (String s : split) {

            //判断菜品是否在售
            Dish<FlavorsById> dish = dishMapper.dishSelectById(s);
            if (dish == null){
                log.warn("当前查询菜品为空");
                throw new CustomException(Code.NO_CONTENT, "当前查询菜品为空");
            }
            if (dish.getStatus()==1){
                log.warn("当前菜品已启售，无法删除");
                throw new CustomException(Code.FORBIDDEN, "当前菜品已启售，无法删除");
            }

            //判断菜品是否存在于套餐中
            List<SetmealDish> list = setmealMapper.setmealDishSelectById(s);
            if (list.size()>0){
                return JsonResult.error("该菜品已被套餐绑定");
            }

            //删除菜品口味
            dishMapper.flavorsDeleteById(s);
            //删除菜品
            int i = dishMapper.dishDeleteById(s);

            count = count+ i;
        }

        if (count == split.length) {
            return JsonResult.success("删除菜品成功");
        } else {
            return JsonResult.error("删除菜品失败");
        }
    }

    //通过所属分类id查询菜品（下拉查询）
    public JsonResult<List<Dish<FlavorsById>>> dishSelectByCategoryId(String categoryId){

        List<Dish<FlavorsById>> dishes = dishMapper.dishSelectByCategoryId(categoryId);

        Category category = categoryMapper.categorySelectById(categoryId);


        //查询口味并添加分类名
        for (Dish<FlavorsById> dish : dishes) {

            //添加分类名
            dish.setCategoryName(category.getName());

            List<FlavorsById> flavorsByIds = dishMapper.flavorsSelectById(dish.getId());
            dish.setFlavors(flavorsByIds);
        }

        if (dishes.size()>0){
            return JsonResult.select(dishes,"查询成功");
        }else {
            return JsonResult.select(dishes,"暂无数据");
        }
    }

    //通过菜品id修改状态
    public int dishUpdateStatusById(String id ,Integer status){

        return dishMapper.dishUpdateStatusById(id,status);
    }

}
